using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Ec.NETCoreFramework.Common.MQ;
using Ec.NETCoreFramework.Common.Plug.Core;
using Ec.NETCoreFramework.Common.Plug.QuartzService;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;

namespace Ec.NETCoreFramework.Common.Plug.MQService
{
    public class Program
    {
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables()
        .Build();

        public static void Main(string[] args)
        {
            string path = Path.Combine(Directory.GetCurrentDirectory(), "log",
                        "Ec.NETCoreFramework.Common.Plug.MQService");
            const string outputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss.FFF}-{RequestId} {Level}] {Message}({SourceContext:l}){NewLine}{Exception}";
            var sentryUrl = Configuration.GetValue<string>("SentryUrl");
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(Configuration)
                .Enrich.FromLogContext()
                .Enrich.WithThreadId()
                 .WriteTo.Sentry(sentryUrl, serverName: "mq-service", environment: Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), minimumBreadcrumbLevel: LogEventLevel.Information, minimumEventLevel: LogEventLevel.Information)
                .WriteTo.File(path, rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, outputTemplate: outputTemplate)
                .CreateLogger();

            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    
                    var v = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                    if (string.IsNullOrEmpty(v))
                    {
                        v = "Production";
                    }
                    var appConfig = (new ConfigHelper().Get<AppConfig>("appconfig", v) ?? new AppConfig());

                    services.AddSingleton(appConfig);

                    services.AddSingleton(new AppsettingsHelper(hostContext.HostingEnvironment.ContentRootPath));

                    //services.AddSingleton<MsgConsume, MsgConsume>(p=> new MsgConsume(appConfig.MQConf.Server, appConfig.MQConf.UserName, appConfig.MQConf.Pwd, appConfig.MQConf.VirtualHost));
                    //services.AddHostedService<MQHostedService>();
                    services.AddHostedService<Worker>();
                });
    }
}
